# -*- coding: utf-8 -*-
import requests
import time
"""行情获取基类"""
class  StocksRequest:

    def __init__(self):
       headers = {
            'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding':'gzip, deflate, sdch',
            'Accept-Language':'zh-CN,zh;q=0.8',
            'Connection':'keep-alive',
            'Upgrade - Insecure - Requests': '1',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.100 Safari/537.36'
        }
       self.股票数据 = dict();
       self._session = requests.Session()
       self._session.headers.update(headers)
       self.雪球数据会话()

    def 雪球数据会话(self):
       stock_api = 'https://xueqiu.com/user/refreshCookie'
       r =  self._session.get(stock_api,timeout=5)
       self.cookies = dict(xq_a_token=r.cookies.get('xq_a_token'), xq_r_token=r.cookies.get('xq_r_token'))
    def 雪球实时数据(self,股票代码):
        stock_api = 'https://xueqiu.com/v4/stock/quote.json'
        if 股票代码.startswith('0'):
            _股票代码 = 'SZ' + 股票代码
        else:
            _股票代码 = 'SH' + 股票代码

        cookies = dict(xq_a_token='0e2211c7473b15a8d106ecc2a47e46cbb6176d5d', xq_r_token='bc856423be434f937f5b329b6597dfd6897fb9c0')
        params = {'code': _股票代码}
        r = self._session.get(stock_api, params=params, cookies=cookies, timeout=5)
        r_json = r.json()
        self.股票数据[股票代码] = self.解析雪球实时数据(_股票代码,r_json)
        return self.股票数据

    def 解析雪球实时数据(self,_股票代码,response_data):
        _valueList = response_data[_股票代码]
        _实时数据 = dict();
        _实时数据['股票名称'] = _valueList['name']
        _实时数据['股票代码'] = _valueList['symbol']
        _实时数据['市场代码'] = _valueList['exchange']
        _实时数据['开盘价'] = float(_valueList['open'])
        _实时数据['当前价'] = float(_valueList['current'])
        _实时数据['低价'] = float(_valueList['low'])
        _实时数据['高价'] = float(_valueList['high'])


        _实时数据['涨跌'] = _valueList['percentage']
        _实时数据['振幅'] = _valueList['amplitude']
        _实时数据['总量'] = float(_valueList['volume'])
        _实时数据['总额'] = float(_valueList['amount'])
        _实时数据['涨停价'] = float(_valueList['rise_stop'])
        _实时数据['跌停价'] = float(_valueList['fall_stop'])
        _实时数据['总市值'] = float(_valueList['marketCapital'])
        _实时数据['总股本'] = float(_valueList['totalShares'])
        _实时数据['流通股本'] = float(_valueList['fall_stop'])
        _实时数据['上一个交易日收盘价'] = float(_valueList['last_close'])
        return _实时数据

    def _处理股票代码(self,股票代码):
        if 股票代码.startswith('0'):
            _股票代码 = 'SZ'+股票代码
        else:
            _股票代码 = 'SH' + 股票代码
        return  _股票代码

    def 雪球分时数据(self,股票代码):
        stock_api = "https://xueqiu.com/stock/forchart/stocklist.json"
        _股票代码 = self._处理股票代码(股票代码)
        cookies = dict(xq_a_token='0e2211c7473b15a8d106ecc2a47e46cbb6176d5d', xq_r_token='bc856423be434f937f5b329b6597dfd6897fb9c0')
        params={'symbol': _股票代码, 'period': '1d','one_min':'1'}
        r = self._session.get(stock_api, params=params, cookies=cookies, timeout=5)
        r_json = r.json()
        self.股票数据[股票代码] = self.解析雪球分时数据(r_json)
        return self.股票数据

    def 雪球K线数据(self,股票代码,begin,end):

        stock_api = "https://xueqiu.com/stock/forchartk/stocklist.json"
        _股票代码 = self._处理股票代码(股票代码)
        cookies = dict(xq_a_token='0e2211c7473b15a8d106ecc2a47e46cbb6176d5d', xq_r_token='bc856423be434f937f5b329b6597dfd6897fb9c0')
        params = {'symbol': _股票代码, 'period': '1d', 'type': 'normal','begin':begin,'end':end}
        r = self._session.get(stock_api, params=params, cookies=cookies, timeout=5)
        r_json = r.json()
        self.股票数据[股票代码] = self.解析雪球K线数据(r_json)
        return self.股票数据

    def 解析雪球K线数据(self,response_data):
        _keyValueList = response_data['chartlist']
        _K线数据 = {};
        _K线数据['日K线数据']= []
        _收盘价 = []
        _MACD = []
        _成交量 = []
        print(_keyValueList)
        for data in _keyValueList:
            _每日K线数据 = {}
            _每日K线数据['开盘价'] = float(data['open'])
            _每日K线数据['收盘价'] = float(data['close'])
            _每日K线数据['最高价'] = float(data['high'])
            _每日K线数据['最低价'] = float(data['low'])
            _每日K线数据['成交量'] = float(data['volume'])
            _每日K线数据['5日'] = float(data['ma5'])
            _每日K线数据['10日'] = float(data['ma10'])
            _每日K线数据['20日'] = float(data['ma20'])
            _每日K线数据['30日'] = float(data['ma30'])
            _每日K线数据['macd'] = float(data['macd'])
            _每日K线数据['dif'] = float(data['dif'])
            _每日K线数据['dea'] = float(data['dea'])
            _收盘价.append(float(data['close']))
            _MACD.append(float(data['macd']))
            _成交量.append(float(data['volume']))
            _K线数据['日K线数据'].append(_每日K线数据)
        _K线数据['周期最高价'] = max(_收盘价)
        _K线数据['周期最低价'] = min(_收盘价)
        _K线数据['周期MACD高值'] = max(_MACD)
        _K线数据['周期MACD低值'] = min(_MACD)
        _K线数据['周期成交量高值'] = max(_成交量)
        _K线数据['周期成交量低值'] = max(_成交量)
        return _K线数据

    def 解析雪球分时数据(self,response_data):
        _timelyList = response_data['chartlist']

        _分时数据 = dict();
        _分时数据['价格'] = []
        _分时数据['成交量'] = []
        _分时数据['均价'] = []
        for data in _timelyList:
            _分时数据['价格'].append(float(data['current']))
            _分时数据['成交量'].append(float(data['volume']))
            _分时数据['均价'].append(float(data['avg_price']))

        return _分时数据

    def 盘口数据(self, 股票代码):
        stock_api = "https://app.leverfun.com/timelyInfo/timelyOrderForm"
        params = dict(stockCode=股票代码)

        r = self._session.get(stock_api, params={'stockCode': 股票代码}, timeout=5)
        r_json = r.json()
        self.股票数据[股票代码] = self.解析盘口数据(r_json)
        return self.股票数据

    def 解析盘口数据(self, response_data):
        data = response_data['data']
        buys = data['buyPankou']
        sells = data['sellPankou']
        _盘口数据 = dict(
            close=round(data['preClose'], 3),
            now=data['match'],
            buy=buys[0]['price'],
            sell=sells[0]['price'],
        )
        for trade_info_li, name in zip([sells, buys], ['ask', 'bid']):
            for i, trade_info in enumerate(trade_info_li):
                _盘口数据['{name}{index}'.format(name=name, index=i + 1)] = trade_info['price']
                _盘口数据['{name}{index}_volume'.format(name=name, index=i + 1)] = int(trade_info['volume'])
        return _盘口数据

    def __del__(self):
        if self._session is not None:
            self._session.close()

if __name__ == '__main__':
    q = StocksRequest()
    print(q.雪球分时数据('002373'))



